<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row class="query-form" style="padding-top: 10px" v-show="!switchFlag">
                <Col span="8">
                    <FormItem label="设备名称：" prop="equipName">
                        <Input class="query-form-el" type="text" v-model="form1.equipName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="设备型号：" prop="specification">
                        <Input class="query-form-el" type="text" v-model="form1.specification"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form" style="padding-top: 10px">
                <Col span="8">
                    <FormItem label="设备名称：" prop="equipName">
                        <Input class="query-form-el" type="text" v-model="form1.equipName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="设备型号：" prop="specification">
                        <Input class="query-form-el" type="text" v-model="form1.specification"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="生产厂家：" prop="supplyFacturName">
                        <Input class="query-form-el" type="text" v-model="form1.supplyFacturName"></Input>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="所在位置：" prop="location">
                        <Input class="query-form-el" type="text" v-model="form1.location"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="所属单位：" prop="orgName">
                        <Input class="query-form-el" type="text" v-model="form1.orgName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>

            <Row class="query-form">
                <Col span="24">
                    <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                </Col>
            </Row>
        </Form>

        <Table ref='table' :height="tableHeight" :loading="loading" size="small" no-data-text="没有查询到相关数据!"
               @on-selection-change='getSelectRows'
               border :columns="columns1" :data="dataTable">
        </Table>


        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>

        <Modal :title="add ? '消防设备新增':'消防设备修改'" :transfer=false v-model="model1" :width=600>
            <Row>
                <Col span="24">
                    <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="设备名称：" prop="equipName">
                                    <Input type="text" v-model="form1datacopy.equipName"></Input>
                                </FormItem>
                            </Col>

                            <Col span="7">
                                <FormItem label="编号：" prop="faciNo">
                                    <Input type="text" v-model="form1datacopy.faciNo"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="所在位置：" prop="location">
                                    <Input type="text" v-model="form1datacopy.location"></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="规格型号：" prop="specification">
                                    <Input type="text" v-model="form1datacopy.specification"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="数量：" prop="eqipNumber">
                                    <Input type="text" v-model="form1datacopy.eqipNumber"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="生产日期：" prop="producDate">
                                    <Date-picker type="date" placeholder="选择日期"
                                                 v-model="form1datacopy.producDate"></Date-picker>
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="状态：" prop="state">
                                    <Select v-model="form1datacopy.state">
                                        <Option v-for="item in stateList" :value="item.codingCodeId"
                                                :key="item.codingCodeId">{{ item.codingName }}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="生产厂家：" prop="supplyFactur">
                                    <Input type="text" readonly @on-focus="openSupplyModel"
                                           v-model="form1datacopy.supplierName"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="检定日期：" prop="verificationDate">
                                    <Date-picker type="date" placeholder="选择日期"
                                                 v-model="form1datacopy.verificationDate"></Date-picker>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="相关参数(性能)：" prop="performance">
                                    <Input type="text" v-model="form1datacopy.performance"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="统计人：" prop="statistician">
                                    <Select
                                            v-model="form1datacopy.statistician"
                                            filterable
                                            :remote-method="remoteMethod1"
                                            :loading="loading1">
                                        <Option v-for="(option, index) in options1" :value="option.userId"
                                                :label="option.userName" :key="index">
                                            <span>{{option.userName}}</span>
                                            <span style="float:right;color:#ccc">{{option.orgInfo.orgName}}</span>
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="7">

                            </Col>


                        </Row>
                        <!-- <Row type="flex" justify="space-around" class="code-row-bg">
                             <Col span="23" >
                                 <FormItem>
                                     <Button type="primary"  class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')" >确定</Button>
                                     <Button type="primary"  class='ivu-btn-cancel' @click="handleCancel"  >取消</Button>
                                 </FormItem>
                             </Col>
                         </Row>-->
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')">
                    确定
                </Button>
                <Button type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
            </div>
        </Modal>

        <Modal title="供应商" :transfer=false footer-hide v-model="suppliersForSelect" :width=900>
            <SuppliersForSelect @getSelectData="getSelectData">
            </SuppliersForSelect>
        </Modal>

        <Modal title="消防设备详情" class="modal-view-detail" :transfer=false v-model="model2" :width=1100>
            <Row>
                <Col span="24">
                    <Form :model="showdata" :label-width="160">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="设备名称：" prop="equipName">
                                    {{showdata.equipName}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="编号：" prop="faciNo">
                                    {{showdata.faciNo}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="所在位置：" prop="location">
                                    {{showdata.location}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="规格型号：" prop="specification">
                                    {{showdata.specification}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="数量：" prop="eqipNumber">
                                    {{showdata.eqipNumber}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="生产日期：" prop="producDate">
                                    {{showdata.producDate}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="状态：" prop="stateName">
                                    {{showdata.stateName}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="生产厂家：" prop="supplierName">
                                    {{showdata.supplierName}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="检定日期：" prop="verificationDate">
                                    {{showdata.verificationDate}}
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="相关参数(性能)：" prop="performance">
                                    {{showdata.performance}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="统计人：" prop="userName">
                                    {{showdata.userName}}
                                </FormItem>
                            </Col>
                            <Col span="7" offset="1">
                                <FormItem label="所属部门：" prop="orgName">
                                    {{showdata.orgName}}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>

            <div slot="footer">
                <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
            </div>
        </Modal>
    </layout>
</template>

<script>
    import {Api} from '../../../../api/index.js'
    import cascaderDom from "../../../../components/cascader-dom.vue"
    import SuppliersForSelect from "./suppliersForSelect";
    import {sessionStorage} from '../../../../common/cacheUtils.js';

    export default {
        components: {
            SuppliersForSelect,
            cascaderDom
        },
        data() {
            return {
                switchFlag: false,
                buttonLoading: false, suppliersForSelect: false,
                upUrl: Api.uploadPTWSchemeFile,
                form1: {
                    chemicalsName: '',
                    hazardCategory: ''
                },
                setCurrentName: {},
                //分页参数
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {
                        width: 150,
                        title: '设备名称',
                        align: 'center',
                        key: 'equipName',
                    },
                    {
                        width: 200,
                        title: '编号',
                        align: 'center',
                        key: 'faciNo',
                    },
                    {
                        width: 300,
                        title: '所在位置',
                        key: 'location',
                        align: 'center'
                    },
                    {
                        width: 150,
                        title: '规格型号',
                        key: 'specification',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '数量',
                        key: 'eqipNumber',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '生产日期',
                        key: 'producDate',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                (this.formatDate(new Date(params.row.producDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },
                    {
                        width: 100,
                        title: '状态',
                        key: 'stateName',
                        align: 'center'
                    },
                    {
                        width: 300,
                        title: '生产厂家',
                        key: 'supplierName',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '检定日期',
                        key: 'verificationDate',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                (this.formatDate(new Date(params.row.verificationDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },
                    {
                        width: 200,
                        title: '相关参数(性能)',
                        key: 'performance',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '统计人',
                        key: 'userName',
                        align: 'center'
                    },
                    {
                        width: 150,
                        title: '所属部门',
                        key: 'orgName',
                        align: 'center'
                    },

                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                ruleCustom: {
                    equipName: [
                        {required: true, message: '  ', trigger: 'blur'}
                    ],
                    faciNo: [
                        {required: true, message: '  ', trigger: 'blur'}
                    ],
                    location: [
                        {required: true, message: '  ', trigger: 'blur'}
                    ],
                    specification: [
                        {required: true, message: '  ', trigger: 'blur'}
                    ],
                    eqipNumber: [{
                        validator: (rule, value, callback) => {
                            if (!(/^\d+$/.test(value))) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    producDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    verificationDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    state: [
                        {required: true, message: '  ', trigger: 'change'}
                    ],
                    supplyFactur: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    performance: [
                        {required: true, message: '  ', trigger: 'blur'}
                    ],
                    statistician: [
                        {required: true, message: '  ', trigger: 'change'}
                    ],

                },
                currentOrgId: '',
                currentOrgName: '',
                form1datacopy: {},
                options1: [],
                stateList: [],
                dataTable: [],
                showdata: {},
                model1: false,
                model2: false,
                loading1:false,
                add: false,
                hazardCategoryList: [],
                tableHeight: 150, loading: false,
                deleteRows: [],
                file: null,
                fileName: null,
                downloadUrl: Api.downloadPTWSchemeFile,
            }
        },
        mounted: function () {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            //this.selectCodingSort();
            this.selectCodingSort();
            this.query();
        },
        methods: {

            beforeUpload(file) {
                this.file = file;
                this.fileName = file.name;
                return false;
            },

            getSelectData(row) {
                this.form1datacopy.supplyFactur = row.supplierId;
                this.form1datacopy.supplierName = row.supplierName;
                this.suppliersForSelect = false;
            },
            openSupplyModel() {
                this.suppliersForSelect = true;
            },

            selectCodingSort() {
                this.$http.get(Api.queryCodeDetailBySortId + '/STATE-000001', {params: {}}).then((res) => {
                    this.stateList = res.data.data;
                })
            },
            remoteMethod1(query) {
                if (query !== '') {
                    clearTimeout(this.remoteMethod1.timer);
                    this.remoteMethod1.timer = setTimeout(() => {
                        this.options1.splice(0, this.options1.length);
                        this.loading1 = true;
                        let data = {
                            userName: query,
                            orgId: sessionStorage('userId').getObject('userId').orgInfo.parentId
                        };
                        this.$http.get(Api.queryUserByUserName, {params: data}).then((res) => {
                            this.loading1 = false;
                            res.data.data.forEach(item => {
                                this.options1.push(item);
                            })

                        }).catch(e => {
                            this.loading1 = false;
                        })
                    }, 200);
                } else {
                    this.options1 = [];
                }
            },
            setOrgId(data) {
                this.form1datacopy.tenanceUnit = data[data.length - 1];
            },
            setOrgName(data) {
                this.form1datacopy.tenanceUnitName = data;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            setUserName(data) {
                this.form1datacopy.userName = data;
            },
            setUserId(data) {
                this.form1datacopy.statistician = data[data.length - 1];
            },

            copyArray(arr) {
                return JSON.parse(JSON.stringify(arr));
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },

            showData(data, flag) {
                this.currentOrgId = data.row.tenanceUnit;
                this.currentOrgName = data.row.tenanceUnitName;
                if (flag == 1) {
                    //查看页面
                    this.showdata = data.row;
                    this.model2 = true;
                    this.showdata.verificationDate = this.formatDate(new Date(this.showdata.verificationDate), 'yyyy-MM-dd')
                    this.showdata.producDate = this.formatDate(new Date(this.showdata.producDate), 'yyyy-MM-dd')
                } else {
                    this.setCurrentName = {value: data.row.statistician, label: data.row.userName};
                    //修改页面
                    this.form1datacopy = Object.assign(data, JSON.parse(JSON.stringify(data.row)));
                    this.add = false;
                    this.model1 = true;
                }
            },

            getSelectRows(rows) {
                this.deleteRows = rows;
            },

            deleteData(params) {
                let url = Api.deleteFireControlBook;
                this.$http.delete(url + '/' + params.row.equipId, {params: {}}).then((res) => {
                    this.$Message.success('成功');
                    this.query()
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })
            },

            query() {
                this.loading = true;
                let parentId = sessionStorage('userId').getObject('userId').orgInfo.parentId;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    equipClass: '1',
                    orgId: parentId,
                };

                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.queryFireControlBook;
                this.$http.get(url, {params: data}).then((res) => {
                    if (res.data.status == 200) {
                        console.log(res.data.data.data);
                        this.dataTable = res.data.data.data;
                        this.pagedata.total = res.data.data.totalSize;
                        this.loading = false;
                    } else {
                        this.$Message.error("数据获取失败")
                    }
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            reset() {
                this.form1 = {}
            },
            handleCancel() {
                this.form1datacopy = {};
                this.model1 = false;
            },
            submit() {
                this.$refs['form1datacopy'].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                        let userId = sessionStorage('userId').getObject('userId').userId;
                        if (this.add) {
                            this.form1datacopy.createUserId = userId;
                            this.form1datacopy.createOrgId = orgId;
                            this.form1datacopy.equipClass = '1';
                            this.$http.post(Api.saveFireControlBook, this.form1datacopy).then((res) => {
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                                this.buttonLoading = false
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.buttonLoading = false
                                this.$Message.error("数据获取失败")
                            })
                        } else {
                            this.form1datacopy.updateUserId = userId;
                            this.form1datacopy.updateOrgId = orgId;
                            this.$http.post(Api.updateFireControlBook, this.form1datacopy).then((res) => {
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                                this.buttonLoading = false
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.buttonLoading = false
                                this.$Message.error("数据获取失败")
                            })
                        }

                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            addInfo() {
                let userId = sessionStorage('userId').getObject('userId').userId;
                let userName = sessionStorage('userId').getObject('userId').userName;
                this.setCurrentName = {value: userId, label: userName};
                this.form1datacopy = {
                    statistician: userId,
                    userName: userName,
                };
                this.add = true;
                this.model1 = true;
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        },
        watch: {
            /*  tableHeight(){
                  this.tableHeight = window.innerHeight - 360 - 48;
              },*/
            "model1": function (qw, er) {
                if (qw && this.model1) {
                    setTimeout(() => {
                        this.$refs.childUser.setCurrentUser();
                    }, 100)
                } else {
                    this.$refs.childUser.setCurrentUser();
                }
            }
        },
    }
</script>
<style lang='css' scoped>
    @import '../../../../index.css';
</style>
